package sheduler;

import java.util.Calendar;
import java.util.TimerTask;
import java.util.logging.Logger;

import server.Server;
import smtp.SmtpSender;

public class EmailTask extends TimerTask{
	String emailTo;
	String emailFrom;
	String emailMessage;
	String emailSubject;
	String status;
	
	// Times
	long submissionTime;
	long sendingTime;
	
	// Status
	boolean sent;
	int delay;
	SmtpSender sender;
	
	public EmailTask(SmtpSender sender, String from, String to, String subject, String message, int delay) {
		this.sender = sender;
		this.emailTo = to;
		this.emailFrom = from;
		this.emailSubject = subject;
		this.emailMessage = message;
		this.sent = false;
		this.delay = delay;
		this.status = "Scheduled";
		
		Calendar cal = Calendar.getInstance();
		this.submissionTime = cal.getTimeInMillis();		
		
		this.sendingTime = this.submissionTime + delay * 1000;
	}
	
	
	public long getSubmissionTime() {
		return this.submissionTime;
	}
	
	public long getSendingTime() {
		return this.sendingTime;
	}
	
	
	public int getDelay() {
		return this.delay;
	}
	
	// How much time is remaining
	public long getRemainingTime(long curtime) {
		long tt = (this.sendingTime - curtime) / 1000;
		if (tt < 0) {
			return 0;
		}
		else {
			return tt;
		}
	}	
	
	public String getSubject() {
		return this.emailSubject;
	}
	
	public String getSender() {
		return this.emailFrom;
	}
	
	public String getReceiver() {
		return this.emailTo;
	}
	
	public void execute() {
		this.sent = true;
	}
	
	// Should we send this email now
	public boolean isSendable(long curtime) {
		if ((!this.sent) && (this.submissionTime >= curtime)) {
			return true;
		}
		return false;
	}

	public boolean isSent() {
		return sent;
	}

	public String getStatus() {
		return this.status;
	}
	
	public void confirmation(String msg) {
		try {
			String body = "Email was submitted for sending (" + emailSubject + ").\n";
			body += msg;
			this.sender.sendMail(SmtpSender.SENDER, emailFrom, "Email sending status", body);
		}
		catch (Exception e) {
			Logger.getLogger(Server.LOG).severe("Cannot sent confirmation: " + e.getLocalizedMessage());
		}
	}
	
	@Override
	public void run() {					
		try {
			this.sender.sendMail(emailFrom, emailTo, emailSubject, emailMessage);
			this.sent = true;			
			confirmation("SUCCESS. Email sent successfully.");
			this.status = "Sent";
		} catch (Exception e) {
			confirmation("FAIL. Email sent failed: " + e.getMessage());
			this.status = e.getMessage();
		}				
	}
	
}
